<template>
  <div class="shop-detail-container">
    <!-- 商家头部信息 -->
    <div class="shop-header">
      <div class="header-back" @click="router.back()">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      
      <div class="header-content">
        <!-- 商家头像 -->
        <img :src="getImageUrl(merchant.avatar_path)" class="shop-avatar" alt="商家头像">
        
        <!-- 商家基本信息 -->
        <div class="shop-info">
          <div class="info-top">
            <h2 class="shop-name">{{ merchant.name }}</h2>
            <div class="shop-distance">
              <el-icon><Location /></el-icon>
              <span>{{ merchant.distance }}km</span>
            </div>
          </div>
          
          <!-- 商家描述 -->
          <div class="shop-description" v-if="merchant.description">
            <el-icon><InfoFilled /></el-icon>
            <span>{{ merchant.description }}</span>
          </div>
          
          <!-- 商家地址 -->
          <div class="shop-address">
            <el-icon><MapLocation /></el-icon>
            <span>{{ merchant.address }}</span>
          </div>
          
          <!-- 商家电话 -->
          <div class="shop-phone" v-if="merchant.phone">
            <el-icon><Phone /></el-icon>
            <span>{{ merchant.phone }}</span>
            <el-button type="primary" size="small" class="call-btn" @click="callMerchant">
              拨打电话
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品分类和商品列表 -->
    <div class="shop-main">
      <!-- 左侧分类导航 -->
      <div class="category-nav">
        <div
          v-for="category in categories"
          :key="category.name"
          class="category-item"
          :class="{ 'active': activeCategory === category.name }"
          @click="activeCategory = category.name"
        >
          {{ category.name }}
        </div>
      </div>

      <!-- 右侧商品列表 -->
      <div class="food-list-container">
        <div
          v-for="category in categories"
          :key="category.name"
          v-show="activeCategory === category.name"
          class="food-category"
        >
          <h3 class="category-title">{{ category.name }}</h3>
          <div class="food-items">
            <div
              v-for="food in category.foods"
              :key="food.dishId"
              class="food-item"
            >
              <div class="food-image">
                <img :src="getImageUrl(food.imageUrl)" alt="商品图片">
              </div>
              <div class="food-info">
                <h3 class="food-name">{{ food.name }}</h3>
                <p class="food-desc" v-if="food.description">{{ food.description }}</p>
                <div class="food-price">
                  <span class="now-price">¥{{ food.price }}</span>
                </div>
              </div>
              <div class="food-control">
                <CartControl 
                  :food="food" 
                  @add="addToCart" 
                  @remove="removeFromCart" 
                  :disabled="isTooFar"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 购物车 -->
    <ShopCart
    :selected-foods="selectedFoods"
    :delivery-price="deliveryFee"
    :min-price="minOrderAmount"
    :disabled="isTooFar"
    :merchant-id="merchant.merchantId"
    :merchant-name="merchant.name"
    :merchant-avatar="merchant.avatar_path"
  />
    
    <!-- 距离过远提示 -->
    <div class="distance-warning" v-if="isTooFar">
      <el-alert type="warning" show-icon :closable="false">
        距离过远({{ merchant.distance }}km)，不支持配送
      </el-alert>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { API_BASE_URL } from '@/config';
import CartControl from '@/components/ShopCart/CartControl.vue';
import ShopCart from '@/components/ShopCart/ShopCart.vue';
import { ArrowLeft, InfoFilled, Location, Phone, MapLocation } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();

// 商家数据（从路由参数获取）
const merchant = ref({
  merchantId: route.params.merchantId,
  phone: route.query.phone,
  description: route.query.description,
  address: route.query.address,
  name: route.query.name || '',
  leastprice:route.query.leastprice,
  avatar_path: route.query.avatar || '',
  distance: parseFloat(route.query.distance).toFixed(2) || 0
});

// 拨打电话
const callMerchant = () => {
  if (merchant.value.phone) {
    window.location.href = `tel:${merchant.value.phone}`;
  }
};

// 配送费和最小订单金额
const deliveryFee = computed(() => {
  if (merchant.value.distance <= 1) return 2;
  if (merchant.value.distance <= 3) return 3;
  if (merchant.value.distance <= 5) return 4;
  return 0; // 超过5km不支持配送
});

const minOrderAmount = merchant.value.leastprice; // 最小起送金额
const isTooFar = computed(() => merchant.value.distance > 5);

// 商品分类和食品数据
const dishes = ref([]);
const categories = computed(() => {
  const categoryMap = {};
  
  dishes.value.forEach(dish => {
    if (!categoryMap[dish.classname]) {
      categoryMap[dish.classname] = {
        name: dish.classname,
        foods: []
      };
    }
    categoryMap[dish.classname].foods.push(dish);
  });
  
  return Object.values(categoryMap);
});

const activeCategory = ref('');

// 购物车数据
const cart = ref({});

// 获取图片完整URL
const getImageUrl = (path) => {
  if (!path) return require('@/assets/default-merchant.jpg');
  return `${import.meta.env.VITE_API_BASE_URL}${path}`;
};

// 获取商家菜品
const fetchDishes = async () => {
  try {
    const response = await axios.post(`${API_BASE_URL}/dishes/getlist`, null, {
      params: {
        merchantid: merchant.value.merchantId
      }
    });
    
    dishes.value = response.data.map(dish => ({
      ...dish,
      count: 0 // 初始化购物车数量
    }));
    
    // 设置默认激活的分类
    if (categories.value.length > 0) {
      activeCategory.value = categories.value[0].name;
    }
  } catch (error) {
    console.error('获取菜品失败:', error);
  }
};

// 添加到购物车
const addToCart = (food) => {
  if (isTooFar.value) return;
  
  if (!cart.value[food.dishId]) {
    cart.value[food.dishId] = { ...food, count: 0 };
  }
  cart.value[food.dishId].count++;
  food.count++;
};

// 从购物车移除
const removeFromCart = (food) => {
  if (cart.value[food.dishId] && cart.value[food.dishId].count > 0) {
    cart.value[food.dishId].count--;
    food.count--;
    if (cart.value[food.dishId].count === 0) {
      delete cart.value[food.dishId];
    }
  }
};

// 计算选中的食品
const selectedFoods = computed(() => {
  return Object.values(cart.value).filter(item => item.count > 0);
});

// 组件挂载时获取数据
onMounted(() => {
  fetchDishes();
});
</script>

<style scoped>
.shop-detail-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  position: relative;
  overflow: hidden;
}

/* 商家头部样式 */
.shop-header {
  position: relative;
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  padding: 15px;
  padding-top: 50px;
  color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header-back {
  position: absolute;
  top: 15px;
  left: 15px;
  font-size: 20px;
  cursor: pointer;
  z-index: 1;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.2);
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-content {
  display: flex;
  align-items: flex-start;
  padding: 10px;
}

.shop-avatar {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  border: 3px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  margin-right: 15px;
  object-fit: cover;
  flex-shrink: 0;
}

.shop-info {
  flex: 1;
  color: #fff;
}

.info-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.shop-name {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.shop-distance {
  display: flex;
  align-items: center;
  font-size: 14px;
  background-color: rgba(0, 0, 0, 0.2);
  padding: 3px 8px;
  border-radius: 12px;
}

.shop-description,
.shop-address,
.shop-phone {
  display: flex;
  align-items: center;
  font-size: 13px;
  margin-bottom: 8px;
  color: rgba(255, 255, 255, 0.9);
}

.shop-description {
  font-style: italic;
}

.shop-phone {
  margin-bottom: 0;
}

.el-icon {
  margin-right: 5px;
  font-size: 14px;
}

.call-btn {
  margin-left: 10px;
  padding: 4px 10px;
  font-size: 12px;
  background-color: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
}

.call-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

/* 商品区域样式 */
.shop-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧分类导航 */
.category-nav {
  width: 90px;
  background-color: #f8f8f8;
  overflow-y: auto;
  flex-shrink: 0;
}

.category-item {
  padding: 15px 5px;
  font-size: 14px;
  color: #666;
  text-align: center;
  border-left: 3px solid transparent;
  cursor: pointer;
  transition: all 0.2s;
}

.category-item.active {
  background-color: #fff;
  color: #ff5339;
  border-left: 3px solid #ff5339;
  font-weight: bold;
}

.category-item:not(:last-child) {
  border-bottom: 1px solid #eee;
}

/* 右侧商品列表 */
.food-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px 15px;
  background-color: #fff;
}

.category-title {
  margin: 0;
  padding: 10px 0;
  font-size: 16px;
  color: #666;
  font-weight: normal;
  border-bottom: 1px solid #f5f5f5;
}

.food-item {
  display: flex;
  padding: 15px 0;
  position: relative;
  border-bottom: 1px solid #f5f5f5;
}

.food-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  flex-shrink: 0;
}

.food-image img {
  width: 100%;
  height: 100%;
  border-radius: 5px;
  object-fit: cover;
}

.food-info {
  flex: 1;
  min-width: 0;
  padding-right: 80px; /* 为购物车按钮留出空间 */
}

.food-name {
  margin: 0;
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.food-desc {
  margin: 5px 0;
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.food-price {
  margin-top: 5px;
}

.now-price {
  font-size: 16px;
  color: #FF5339;
  font-weight: bold;
}

.food-control {
  position: absolute;
  right: 0;
  bottom: 15px;
}

/* 距离提示 */
.distance-warning {
  position: fixed;
  bottom: 60px;
  left: 0;
  right: 0;
  padding: 0 10px;
  z-index: 101;
}
</style>